﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using FineUI;
using Newtonsoft.Json;
using ZHDJ.Core.Util;
using ZHDJ.Data.BLL;
using ZHDJ.Data.Models.Org;
using ZHDJ.WebPage;
using ZHDJ.Data.Models.Common;
using ZHDJ.Core.Log;
using System.Data;
using MySql.Data.MySqlClient;
using ZHDJ.Web.CommonMethod;

namespace ZHDJ.Web
{
    public partial class Login_test : PortalPage
    {
        public string BackUrl
        {
            get
            {
                var tempUrl = (Request.QueryString["ReturnUrl"] ?? "") == ""
                    ? "/Default.aspx"
                    : Server.UrlDecode(Request.QueryString["ReturnUrl"]);
                if (tempUrl.ToLower().Contains("errors"))
                {
                    tempUrl = "/Default.aspx";
                }
                tempUrl = tempUrl.Replace("poundsign", "#");
                #region 特殊处理
                var hdU = Server.UrlDecode(this.hdUrl.Value);
                if (hdU.ToLower().Contains(tempUrl.ToLower() + "#"))
                {
                    var para = hdU.Substring(hdU.IndexOf("#"));
                    tempUrl += para;
                }
                #endregion
                return tempUrl;
            }
        }
        public string CheckLogin
        {
            get
            {

                return Request.QueryString["CheckLogin"] ?? "";
            }
        }

        public string LoginType
        {
            get
            {

                return Request.QueryString["LoginType"] ?? "";
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {

            if (LoginType == "2")
            {
                Check();
                return;
            }
            if (CheckLogin == "1")
            {
                Response.Clear();
                Response.Write(IsLogin ? "1" : "0");
                Response.End();

            }
            if (IsLogin)
            {
                RedirectTo("default", "~/default.aspx");
            }
        }


        #region
        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="user"></param>
        private void LoginSuccess(PartyOrgMember user)
        {
            // 用户所属的角色字符串，以逗号分隔
            string roleIDs = String.Empty;
            if (user.Roles != null)
            {
                roleIDs = String.Join(",", user.Roles.Select(r => r.ID).ToArray());
            }

            bool isPersistent = ckbRe.Checked;
            DateTime expiration = DateTime.Now.AddMinutes(120);
            Session.Timeout = 120;
            CreateFormsAuthenticationTicket(user.LoginID, roleIDs, isPersistent, expiration);
            //加载用户信息，保存在session
            Session["PartyOrgMember"] = user;

            //统计登录人数
            StatisticMethod.StatisticLogin(user);
            //统计在线人数
            StatisticMethod.StatisticOnLine(user);

            //登陆分
            //PartyScoreHelper.Add(() => PartyScoreHelper.AddDayLogin(user.LoginID));

            //修改当前登录人为“第一次登录” = 1
            PartyOrgMember.UpdateIsFirstLogin(user.LoginID, 1);

            AddLog(user.LoginID);

        }

        /// <summary>
        /// 增加登陆日志
        /// </summary>
        public void AddLog(string loginid)
        {

            try
            {
                if (string.IsNullOrEmpty(UserLogID))
                {

                    var log = new PartyUserLoginLog();
                    log.ID = StringHelper.NewID;
                    log.LoginID = loginid;
                    log.LoginIP = Request.UserHostAddress;
                    log.LoginOutTime = null;
                    log.LoginTime = DateTime.Now;
                    log.SessionID = Session.SessionID;
                    log.Source = 1;
                    log.LastOpTime = DateTime.Now;
                    DB.PartyUserLoginLogs.Add(log);
                    DB.SaveChanges();
                    Session["UserLogID"] = log.ID;
                }
                else
                {
                    var log = DB.PartyUserLoginLogs.Find(UserLogID);
                    log.LoginID = loginid;
                    log.LoginTime = DateTime.Now;
                    log.Source = 1;
                    log.LastOpTime = DateTime.Now;
                    DB.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                Log4netHelper.WriteLog("用户登陆日志", ex);
            }
        }

        public void Check()
        {
            long start = 0;
            long end = 0;
            start = DateTime.Now.Ticks;

            string userName = txtLoginName.Text.Trim();
            string password = txtLoginPwd.Text.Trim();

            var loginResult = new LoginResult();
            PartyOrgMember user = DB.PartyOrgMembers.Where(u => u.UserNo == userName).FirstOrDefault();

            if (user != null)
            {
                if (user.IsAgree == null || !(bool)user.IsAgree)
                {
                    //Alert("用户未启用，请联系管理员！");
                    loginResult.IsSuccess = false;
                    loginResult.Message = "用户未启用，请联系管理员！";
                    Log4netHelper.WriteLog(String.Format("登陆失败：用户“{0}”未启用", userName));
                }
                else
                {

                    LoginSuccess(user);
                    loginResult.IsSuccess = true;
                    loginResult.Message = "";
                    var url = WebHost + "/Exam/FrmOtherLogin.aspx?UserID={0}&ValiCode={1}";

                    loginResult.ExamUrl = string.Format(url, userName, GetValiCode(userName));
                    loginResult.BackUrl = BackUrl.ToLower().IndexOf("http://") > 0 ? BackUrl : WebHost + BackUrl;
                    Log4netHelper.WriteLog(loginResult.BackUrl);
                }
            }
            else
            {
                //logger.Warn(String.Format("登陆失败：用户“{0}”不存在", userName));
                loginResult.IsSuccess = false;
                loginResult.Message = "用户名或密码错误";
                Log4netHelper.WriteLog(String.Format("登陆失败：用户“{0}”密码错误", userName));
            }

            end = DateTime.Now.Ticks;

            //Response.Write("<script>alert('end ticks is:" + end + "')</script>");
            //Response.Write("<script>alert('it is:" + (end - start) / 10000000 + "seconds!')</script>");
            //Log4netHelper.WriteLog(String.Format("it is {0} seconds!", (end - start) / 10000000));
            loginResult.Message = ((end - start) / 10000000).ToString();

            Response.Clear();
            Response.Write(JsonConvert.SerializeObject(loginResult));
            Response.End();
        }

        #endregion

        #region 事件
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            Check();
        }
        private string GetValiCode(string userId)
        {
            var md5 = EncryptionUtil.StringToMD5Hash(userId).ToUpper();
            return md5.Substring(0, 5) + md5.Substring(15, 5);
        }
        #endregion

        public class LoginResult
        {
            public LoginResult()
            {
                IsSuccess = false;
                Message = "";
                ExamUrl = "";
                BackUrl = "";
            }

            public bool IsSuccess { get; set; }
            public string Message { get; set; }

            public string ExamUrl { get; set; }

            public string BackUrl { get; set; }
        }
    }


}